<?php

namespace App\Service\OpenShop\Import\OpenFull;

use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserIdentityCardEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\Pay\RmsPayEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftOutfitMappingModel;
use App\Models\OpenShop\ShopCheckAccept\OpenShopCheckAcceptModel;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Remote\Rms\RmsAreaRemote;
use App\Service\OpenShop\Feishu\DesignerEquipmentService;
use App\Service\OpenShop\Feishu\MissionTemplateService;
use App\Service\OpenShop\Feishu\SelectionService;
use App\Service\OpenShop\Feishu\ShopCheckAcceptService;
use App\Service\OpenShop\Feishu\ShopEngineeringConstructionService;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use App\Service\OpenShop\Feishu\StartBusinessService;
use App\Service\OpenShop\Feishu\UserExtContractService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Service\OpenShop\Merchant\SiteMissionService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\SiteLocation\SiteLocationAuditService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\OpenShop\UserBaseInfoService;
use App\Service\OpenShop\UserContractService;
use App\Service\OpenShop\Wap\SignOrderService;
use Illuminate\Support\Facades\Config;

class OpenFullExecute
{
    private OpenFullParam $param;

    public function __construct(OpenFullParam $param)
    {
        $this->param = $param;
    }

    public function execute()
    {
        // 关闭所有的event queue
        Config::set('event.connection', 'sync');
        HistoryOrderParam::$importOrderMode = true;

        if ($this->param->newShop) {

            // 新建
            $stepStatusList = MissionTemplateService::getStepStatusSortLists();
            foreach ($stepStatusList as $stepStatus) {

                $functionName = "step{$stepStatus}";
                $this->$functionName();

                dump("step{$stepStatus} ok...");

                if ($stepStatus == MissionTemplateEnum::STEP_STATUS_18) {
                    dump("shopCode: {$this->param->shopCode} 更新至开业");
                    break;
                }
            }
        } else {

            // 更新字段
            $this->updateColumn();
            dump("shopCode: {$this->param->shopCode} 更新了字段");
        }
    }

    public function doStep(int $stepStatus)
    {
        $functionName = "step{$stepStatus}";
        $this->$functionName();

        dump($functionName . ' success...');
    }

    private function setRmsUserInfoByAuth(?array $userInfo)
    {
        request()->replace(['userInfo' => (object)$userInfo]);
    }

    // 创建订单
    private function step0()
    {
        $this->setRmsUserInfoByAuth($this->param->managerSales);

        $userIdentityCardInfo = [
            'name'               => $this->param->rmsShop['merchantInfo']['username'] ?? '',
            'identityCardNumber' => '',
            'gender'             => UserIdentityCardEnum::GENDER_1,
        ];

        $userBaseInfo = [
            'mobile'                  => $this->param->rmsShop['merchantInfo']['mobile'] ?? '',
            'isSelfWithAddress'       => 0,
            'shopProvinceCode'        => $this->param->siteProvinceCode,
            'chooseShopProvinceCode'  => $this->param->siteProvinceCode,
            'chooseShopCityCode'      => $this->param->siteCityCode,
            'chooseShopDistrictCode'  => $this->param->siteDistrictCode,
            'chooseShopAddressPrefix' => str_replace('/', '-', $this->param->siteMerge),
        ];

        $userExperience = [];

        $do = UserBaseInfoService::insert(getRmsUserInfoByAuth(), $userIdentityCardInfo, $userBaseInfo,
            $userExperience);

        $this->param->orderNo = $do['orderNo'];

        $contractTemplate = OpenShopContractTemplateModel::query()->find($this->param->contractTemplateId);

        $contract = [
            'orderNo'          => $this->param->orderNo,
            'contractors'      => 1, // 个人
            'startTime'        => $this->param->contractStartTime,
            'endTime'          => $this->param->contractEndTime,
            'contractType'     => 1,
            'provideShopCode'  => $this->param->shopCode,
            'policyTemplateId' => $this->param->contractTemplateId,
            'shopCount'        => 1,
        ];

        $do = UserContractService::insert(getRmsUserInfoByAuth(), $contract, false);

        OpenShopSignOrderModel::saveShopTag($this->param->orderNo, [$this->param->shopTag]);
        dump($do);
    }

    // 商家支付
    private function step1()
    {
        $signOrder = OpenShopSignOrderModel::query()->where('orderNo', $this->param->orderNo)->first();

        // 阶段不对
        if ($signOrder->step != SignOrderEnum::STEP_2) {
            throw new \Exception("orderNo:{$this->param->orderNo} step:{$signOrder->step} 阶段异常");
        }

        if ($signOrder->contractRel->shopCount != 1) {
            throw new \Exception("orderNo:{$this->param->orderNo} shopCount:{$signOrder->contractRel->shopCount} 店铺数量错");
        }

        $signOrder->orderType = SignOrderEnum::ORDER_TYPE_IMPORT;
        $signOrder->save();

        // 支付
        OrderService::submitOrderProof((object)[], $this->param->orderNo,
            ['proof' => [['price' => $signOrder->shouldPayPrice, 'img' => '', 'flowNumber' => '', 'payChannel' => CheckEnum::PAY_CHANNEL_BANK]]]);

        $shopId = OpenShopMainProcessModel::query()
                                          ->where('orderNo', $this->param->orderNo)
                                          ->value('shopId');
        if (!$shopId) {
            throw new \Exception('shopId为空');
        }

        // 金额为0时，事后软删除支付流水
        if ($signOrder->shouldPayprice <= 0) {
            $payId = OpenShopSignOrderPayHistoryModel::query()
                                                     ->where('orderNo', $this->param->orderNo)
                                                     ->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_LEAGUE)
                                                     ->where('payStatus',
                                                         OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                                     ->orderByDesc('id')
                                                     ->value('id');

            OpenShopSignOrderPayHistoryModel::deleteData($payId);
        }
    }

    // 商家签约
    private function step2()
    {
        UserExtContractService::updateExtContractStatusAndGenerateShop($this->param->orderNo, 0, 0);
    }

    // 指派开发顾问
    private function step3()
    {
        $dealUid = (int)OpenShopSiteMissionModel::query()
                                                ->where('orderNo', $this->param->orderNo)
                                                ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_3)
                                                ->value('dealUid');

        $rmsUserInfo = (object)RmsUserService::getRmsUserInfoByUserIds([$dealUid])['data'][0] ?? [];


        SelectionService::addManager($this->param->orderNo, $this->param->managerDevelop['id'], $rmsUserInfo);


        // 变更开发顾问
//        $this->setRmsUserInfoByAuth($this->param->managerDesign);
//        $params = (object)[
//            'id' => OpenShopOrderManagerModel::query()->orderByDesc('id')->value('id'),
//            'type' => OpenShopOrderManagerModel::MANAGER_TYPE_2,
//            'managerId' => 1,
//            'managerName' => '夸小父',
//            ];
//        OrderService::changeManager(getRmsUserInfoByAuth(), $params);
    }

    // 选址提交
    private function step4()
    {
        $this->setRmsUserInfoByAuth($this->param->managerDevelop);

        OpenShopSiteLocationModel::query()->where('orderNo', $this->param->orderNo)->update([
            'orderNo'                => $this->param->orderNo,
            'mainProcessId'          => (int)OpenShopMainProcessModel::query()
                                                                     ->where('orderNo', $this->param->orderNo)
                                                                     ->value('id'),
            'chooseShopProvinceCode' => $this->param->siteProvinceCode,
            'cityArea'               => str_replace('/', '-', $this->param->siteMerge),
            'provinceCode'           => $this->param->siteProvinceCode,
            'cityCode'               => $this->param->siteCityCode,
            'areaCode'               => $this->param->siteDistrictCode,
            'address'                => $this->param->siteAddress,
            'cityType'               => RmsAreaRemote::getCityGrade($this->param->siteCityCode)['cityInfo']['grade'] ?? 0,
            'selectTime'             => time(), // 选址日期
            'developConsultantName'  => $this->param->managerDevelopName,
            'developConsultantId'    => $this->param->managerDevelop['id'],
            'openTime'               => $this->param->startBusinessTime,
            'status'                 => SiteLocationEnum::STATUS_0,
            'siteStatus'             => OpenShopSiteLocationModel::SITE_STATUS_2,
            'updatedByUid'           => $this->param->managerDevelop['id'],
            'caseRegisterType'       => $this->param->cashType,
            'area'                   => $this->param->area,
            'rentType'               => SiteLocationEnum::RENT_TYPE_1,
            'fixedRent'              => bcmul($this->param->rent, 100)*12,
            'messageFrom'            => $this->param->messageFrom,
            'siteType'               => $this->param->shopLocationType,
        ]);

        // 选址审批
        $content = '系统默认统一文案...............................';

        (new SiteLocationAuditService())
            ->audit($this->param->orderNo, $content, SiteLocationEnum::STATUS_1, $this->param->managerProvince['id'],
                $this->param->managerProvinceName);

        (new SiteLocationAuditService())
            ->audit($this->param->orderNo, $content, SiteLocationEnum::STATUS_1, $this->param->managerProvince['id'],
                $this->param->managerProvinceName);
    }

    // 商家确认选址
    private function step5()
    {
        $shopId = OpenShopMainProcessModel::query()
                                          ->where('orderNo', $this->param->orderNo)
                                          ->value('shopId');
        if (!$shopId) {
            throw new \Exception('shopId为空');
        }

        $missionId = (int)OpenShopSiteMissionModel::query()
                                             ->where('orderNo', $this->param->orderNo)
                                             ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_5)
                                             ->value('id');

        SiteMissionService::confirmShopLocation($shopId, $missionId, $this->param->confirmLocationTime);
    }

    // 筹备部确认建店信息
    private function step6()
    {
        $this->setRmsUserInfoByAuth($this->param->managerPrepare);

        SpaceDesignService::preparationConfirm($this->param->orderNo, $this->param->managerPrepare['id'],
            $this->param->managerPrepareName);
    }

    // 指派设计师
    private function step7()
    {
        $dealUid = (int)OpenShopSiteMissionModel::query()
                                                ->where('orderNo', $this->param->orderNo)
                                                ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_7)
                                                ->value('dealUid');

        SpaceDesignService::assignSpaceDesign($this->param->orderNo, $this->param->managerDesign['id'],
            $this->param->managerDesignName, $dealUid);
    }

    // 设计模块待确认
    private function step13()
    {
        $this->setRmsUserInfoByAuth($this->param->managerDesign);

        SpaceDesignService::insertSpaceDesignCostData(
            $this->param->orderNo,
            0,
            0,
            0,
            0,
            0,
        );
    }

    // 设计模块支付
    private function step14()
    {
        $sysType = CheckEnum::SYS_TYPE_OPEN_SHOP_DESIGN;
        $design  = OpenShopSpaceDesignCostMappingModel::query()->where('orderNo', $this->param->orderNo)->first();

        $subject = '';
        // 备注: 姓名 + 加盟费
        $username = $this->param->rmsShop['merchantInfo']['username'] ?? '';
        if ($username) {
            $subject .= $username . '-';
        }
        $subject .= RmsPayEnum::SYS_TYPE_TEXT[$sysType];

        // 新增一条支付流水
        $addPayLogId = OpenShopSignOrderPayHistoryModel::addHistory(
            $this->param->orderNo,
            $design->totalFee,
            $design->totalFee,
            OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE,
            OpenShopSignOrderPayHistoryModel::TYPE_FINAL,
            $subject,
            $sysType,
            $design->preparationNo
        );

        // 强制手动支付成功
        (new SignOrderService($this->param->orderNo))->paySuccess($addPayLogId, $design->totalFee);

        // 金额为0时，事后软删除支付流水
        if ($design->totalFee <= 0) {
            OpenShopSignOrderPayHistoryModel::deleteData($addPayLogId);
        }
    }

    // 设计师确认设备模块
    private function step15()
    {
        $this->setRmsUserInfoByAuth($this->param->managerDesign);

        $userInfo = [
            'data' => $this->param->managerDesign,
        ];
//
//        // 不建设备单子
//        $equipments = [
//            [
//                'id'  => 1542,
//                'num' => 1,
//            ]
//        ];
//
//        DesignerEquipmentService::equipmentSave($userInfo, $this->param->orderNo, $equipments);

        event(new SignSiteMissionEvent($this->param->orderNo, MissionTemplateEnum::STEP_STATUS_15,
            $userInfo['data']['id']));
        $processAndAuthUser = DesignerEquipmentService::getMainProcessAndAuthUser($this->param->orderNo);

        event(new OpenShopProcessEvent($processAndAuthUser['rmsUser']->id,
            $processAndAuthUser['order']->mainProcessId, MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN,
            MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_CONFIRM_EQUIPMENT_MODULE));
    }

    // 商家完成设备支付
    private function step16()
    {
        $payPrice = 0;
        $bizId    = '';
        $payNo    = '';

        $sysType    = CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT;
        $payChannel = OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE;

        $addPayLogId = (new SignOrderService($this->param->orderNo, null, false))
            ->internalPaySuccess($bizId, $payPrice, $payChannel, $payNo, $sysType);

        // 金额为0时，事后软删除支付流水
        if ($payPrice <= 0) {
            OpenShopSignOrderPayHistoryModel::deleteData($addPayLogId);
        }
    }

    // 设计师提交整套图
    private function step8()
    {
        $this->setRmsUserInfoByAuth($this->param->managerDesign);

        $orderNo         = $this->param->orderNo;
        $planeCad        = '';
        $planePdf        = '';
        $constructionCad = '';
        $constructionPdf = '';
        $effectImg       = [];
        $softOutfitXlsx  = '';
        $softOutfitFee   = 0;
        SpaceDesignService::uploadDesignMappingData($orderNo, $planeCad, $planePdf, $constructionCad,
            $constructionPdf, $effectImg, []);
    }

    // 商家支付软装模块
    private function step17()
    {
        $sysType = CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE;

        $subject = '';
        // 备注: 姓名 + 加盟费
        $username = $this->param->rmsShop['merchantInfo']['username'] ?? '';
        if ($username) {
            $subject .= $username . '-';
        }
        $subject .= RmsPayEnum::SYS_TYPE_TEXT[$sysType];

        $decorate = OpenShopSpaceDesignSoftOutfitMappingModel::query()->where('orderNo', $this->param->orderNo)
                                                             ->first();

        $payPrice = $decorate->fee;
        $bizId    = $decorate->preparationNo;

        // 新增一条支付流水
        $addPayLogId = OpenShopSignOrderPayHistoryModel::addHistory(
            $this->param->orderNo,
            $payPrice,
            $payPrice,
            OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE,
            OpenShopSignOrderPayHistoryModel::TYPE_FINAL,
            $subject,
            $sysType,
            $bizId
        );

        // 强制手动支付成功
        (new SignOrderService($this->param->orderNo))->paySuccess($addPayLogId, $payPrice);

        // 金额为0时，事后软删除支付流水
        if ($payPrice <= 0) {
            OpenShopSignOrderPayHistoryModel::deleteData($addPayLogId);
        }
    }

    // 筹备部确认施工进场
    private function step9()
    {
        $this->setRmsUserInfoByAuth($this->param->managerPrepare);

        $actuallyParams = (object)[
            'orderNo'                          => $this->param->orderNo,
            'engineeringConstructionStartTime' => time(),
        ];

        ShopEngineeringConstructionService::engineeringConstructionStart(getRmsUserInfoByAuth(), $actuallyParams);
    }

    // 筹备部确认施工完成
    private function step10()
    {
        $this->setRmsUserInfoByAuth($this->param->managerPrepare);
        $finishData = (object)[
            'orderNo'                           => $this->param->orderNo,
            'step'                              => MainProcessEnum::ENGINEER_CONSTRUCT_CONFIRM_FINISH,
            'engineeringConstructionFinishTime' => time(),
            'finishStatus'                      => OpenShopEngineeringConstructionModel::FINISH_STATUS_YES,
        ];

        $attachData = (object)[];

        ShopEngineeringConstructionService::engineeringConstructionFinish(getRmsUserInfoByAuth(), $finishData,
            $attachData);
    }

    // 指派督导
    private function step11()
    {
        $dealUid = (int)OpenShopSiteMissionModel::query()
                                                ->where('orderNo', $this->param->orderNo)
                                                ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_10)
                                                ->value('dealUid');

        $this->setRmsUserInfoByAuth(RmsUserService::getRmsUserInfoByUserIds([$dealUid])['data'][0] ?? []);

        $actuallyParams = (object)[
            'orderNo'     => $this->param->orderNo,
            'managerId'   => $this->param->managerOperate['id'],
            'managerName' => $this->param->managerOperateName,
        ];

        ShopCheckAcceptService::assignManager(getRmsUserInfoByAuth(), $actuallyParams);
    }

    // 督导验收
    private function step12()
    {
        $this->setRmsUserInfoByAuth($this->param->managerOperate);

        $actuallyParams = (object)[
            'orderNo'    => $this->param->orderNo,
            'formSubmit' => '[[{"answer":0},{"answer":0},{"answer":0},{"answer":0},{"answer":0},{"answer":0},{"answer":0},{"answer":0}],[{"answer":0}],[{"answer":0},{"answer":0}],[{"answer":0},{"answer":0},{"answer":0}]]',
        ];

        ShopCheckAcceptService::managerConfirmSubmit(getRmsUserInfoByAuth(), $actuallyParams,
            $this->param->preparationCompleteTime);
    }

    // 提交开业报告
    private function step18()
    {
        $this->setRmsUserInfoByAuth($this->param->managerOperate);

        $params = (object)[
            'orderNo'           => $this->param->orderNo,
            'monthlyWages'      => bcmul($this->param->salary, 100),
            'degreeCooperation' => $this->param->friendly,
            'energy'            => bcmul($this->param->energy, 100),
            'startBusinessTime' => $this->param->startBusinessTime,

        ];

        $attach = (object)[];

        StartBusinessService::submit(getRmsUserInfoByAuth(), $params, $attach);
    }

    // 更新字段
    private function updateColumn()
    {
        // openShop有没有
        $signOrder = OpenShopSignOrderModel::query()
                                           ->where('shopCode', $this->param->shopCode)
                                           ->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)
                                           ->first();

        $this->param->orderNo = $signOrder->orderNo;

        if (!$signOrder) {
            throw new \Exception('signOrder不存在的shopCode');
        }

        $nowStep     = $signOrder->progressRel->nowStepStatus;
        $nowStepSort = MissionTemplateService::getSortByStepStatus($nowStep);

        if ($nowStepSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_5)) {
            OpenShopSiteLocationModel::query()->where('orderNo', $this->param->orderNo)->update([
                'caseRegisterType' => $this->param->cashType,
                'area'             => $this->param->area,
                'rentType'         => SiteLocationEnum::RENT_TYPE_1,
                'fixedRent'        => bcmul($this->param->rent, 100)*12,
                'messageFrom'      => $this->param->messageFrom,
                'openTime'         => $this->param->startBusinessTime,
                'siteType'         => $this->param->shopLocationType,
            ]);
        }

        if ($nowStepSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_18)) {

            OpenShopCheckAcceptModel::query()->where('orderNo', $this->param->orderNo)
                                    ->update(['formSubmitTime' => $this->param->preparationCompleteTime]);
        }

        if ($nowStepSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_999)) {
            OpenShopStartBusinessModel::query()->where('orderNo', $this->param->orderNo)->update([
                'monthlyWages'      => bcmul($this->param->salary, 100),
                'degreeCooperation' => $this->param->friendly,
                'energy'            => bcmul($this->param->energy, 100),
                'startBusinessTime' => $this->param->startBusinessTime,
            ]);
            //同步预计开业时间
            OpenShopSiteLocationModel::query()->where('orderNo', $this->param->orderNo)->update([
                'openTime'         => $this->param->startBusinessTime,
            ]);
        }
    }
}
